/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.settings;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.provider.Settings;
import com.hisense.settings.PowerOffService;
import com.hisense.settings.PowerOnReceiver;
import com.hisense.settings.util.PowerDataGettings;
import com.hisense.settings.util.PreferenceUtils;
import com.hisense.settings.util.Wrapper;
import android.content.SharedPreferences;
import android.preference.Preference;
import com.google.android.tv.mediadevices.MediaDevicesIntents;
import com.hisense.settings.CountDownService;
public class BootCompletedReceiver extends BroadcastReceiver {
    private static final String TAG = "BootCompletedReceiver";

    // Initial wait time for network connections.
    private static final long WAIT_TIME_FOR_NETWORK_MILLIS = 60000;
	public static final String ACTION_TV_ON= "com.hisense.app.device.HISENSE_TVON_STATE";
    private PowerDataGettings mValueStored;
	private static final int IMAGE_MODE_VIVID = 3;
	private static final String KEY_SLEEP_TIMER = "sleep_timer";
	SharedPreferences.Editor editor;
	
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
		final int source = Settings.Secure.getInt(context.getContentResolver(),
                    "power_on_source_num",0);
		Log.d(TAG, "source"+source);
        if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
            // Schedule a alarm to trigger a receiver to check time setting.
            PendingIntent timeCheckIntent = PendingIntent.getBroadcast(context, 0,
                    new Intent(context, TimeCheckingReceiver.class),
                    PendingIntent.FLAG_CANCEL_CURRENT);

            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    android.os.SystemClock.elapsedRealtime() + WAIT_TIME_FOR_NETWORK_MILLIS,
                    AlarmManager.INTERVAL_HOUR, timeCheckIntent);

            // Start TvSettingsObserverService
            try {
            	context.startService(new Intent(context, TvSettingsObserverService.class));
			} catch (Exception e) {
				Log.e(TAG, "start TvSettingsObserverService failed", e);
			}
			// Update passive location provider if the last known location is not set.
            LocationManager locationManager =
                    (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            Location location = locationManager.getLastKnownLocation(
                    LocationManager.PASSIVE_PROVIDER);
            if (location == null) {
                // TODO: try to get address from IP first.
                String zipCode = android.provider.Settings.Secure.getString(
                        context.getContentResolver(), "location_lineup_lookup");
                if (zipCode != null) {
                    Geocoder geocoder = new Geocoder(context, Locale.US);
                    try {
                        List<Address> addresses = geocoder.getFromLocationName(zipCode, 1);
                        if (addresses.isEmpty()) {
                            Log.e(TAG, "No results returned for ZIP code: " + zipCode);
                        } else {
                            String allowMockLocation = Settings.Secure.getString(
                                    context.getContentResolver(),
                                    Settings.Secure.ALLOW_MOCK_LOCATION);
                            Settings.Secure.putString(
                                    context.getContentResolver(),
                                    Settings.Secure.ALLOW_MOCK_LOCATION,
                                    "1");
                            String temporaryProvider = "TemporaryProvider";
                            locationManager.addTestProvider(temporaryProvider,
                                    false, false, false, false, false, false, false, 0, 0);
                            locationManager.setTestProviderEnabled(temporaryProvider, true);
                            location = new Location(temporaryProvider);
                            Address address = addresses.get(0);
                            location.setLatitude(address.getLatitude());
                            location.setLongitude(address.getLongitude());
                            location.makeComplete();
                            locationManager.setTestProviderLocation(temporaryProvider, location);
                            locationManager.removeTestProvider(temporaryProvider);
                            Settings.Secure.putString(
                                    context.getContentResolver(),
                                    Settings.Secure.ALLOW_MOCK_LOCATION,
                                    allowMockLocation);
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Problem with location: " + zipCode, e);
                    }
                }
            }
			//the followed add for hisense PoweroffService
			Intent i = new Intent(context, PowerOffService.class);  
            context.startService(i);
			
			
//			Intent mintent=new Intent(context, CountDownService.class);
//			context.startService(mintent);
//			Log.d(TAG, "getSleepTimerMode------->>>>start "+mintent);
			
			SharedPreferences mSetsleeptimer = context.getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
            editor = mSetsleeptimer.edit();               
            String s=String.valueOf(0);
            editor.putString("sleep_timer", s);                  
            editor.commit();
			
			
/*			if(source!=0){
			
			PowerOnReceiver poweronreceiver=new PowerOnReceiver();
			String  sourceId=poweronreceiver.getSourceUrlString(source);
			Intent poweron=PreferenceUtils.getBootIntent(context.getContentResolver());
			poweron.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
			poweron.putExtra("selected_device_id", Settings.Secure.getString(context.getContentResolver(), "power_on_source"));
			Log.d(TAG, "poweron"+poweron);
			Log.d(TAG, "poweronreceiver.getSourceUrlString(source)"+poweronreceiver.getSourceUrlString(source));
			poweron.putExtra("selected_device_id", sourceId);
            context.startActivity(poweron);
			
			Intent defaultIntent = MediaDevicesIntents.createServiceDefaultDeviceIntent(sourceId);
			context.startService(defaultIntent);
			}
			Intent poweron_receiver=new Intent(context, PowerOnReceiver.class);
            poweron_receiver.setAction("com.google.tv.launcher.HISENSE_POWERON_SETTING");
            context.sendBroadcast(poweron_receiver);
*/			
/*			if(source==1){
            String power_channel=Settings.Secure.getString(context.getContentResolver(), "power_on_channel_uri");
            Log.d(TAG, "power_channel: "+power_channel);
			Uri uri = Uri.parse(power_channel);
            Intent it=new Intent(Intent.ACTION_VIEW ,uri);
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(it);
            }
*/         
        }
		 if(ACTION_TV_ON.equals( intent.getAction())) {
			Log.d(TAG, "mChannelSettingPref------->>>>HISENSE_TVON_STATE ");
			mValueStored = new PowerDataGettings(context);
			Log.d(TAG, "setRetailModeFromBootWizard------->>>>setRetailModeFromBootWizard "+"init");
			if (mValueStored.getCurrentRetailMode()) {
				Wrapper.getWrapperInstance().setAllSourcePictureMode(IMAGE_MODE_VIVID);
				Log.d(TAG, "ImageMode------->>>>ImageMode "+Wrapper.getWrapperInstance().getPictureMode());
			}
		}
    }
}
